import { useState, useEffect, useMemo } from 'react';
import AppList from '../Permission/List';
import TreeList from '../Permission/Tree';
import Permission from '../Permission';
import '../../../style.less';
import { Empty, Spin } from 'antd';
import { getMenuTree, getPermissionList } from '../../../service';
import { TextWidget } from '@inbiz/react';

const Menu = (props: any) => {
  const { appList, permConfig, containerHeight } = props;
  const [outId, $outId] = useState(appList[0]?.OutId); // 应用Id
  const [selectedTreeKeys, $selectedTreeKeys] = useState([]); // 菜单Id
  const [loadding1, $loadding1] = useState(false); //菜单加载
  const [permissionList, $permissionList] = useState([]); //权限列表
  const [treeList, $treeList] = useState([]);

  // 站点点击，获取对应的菜单
  useEffect(() => {
    getMenuTreeFun();
  }, [outId]);

  // 菜单数据change，初始化选中节点
  useEffect(() => {
    $selectedTreeKeys([treeList[0]?.OutId]);
  }, []);

  // 菜单选中，获取对应的权限
  useEffect(() => {
    $permissionList([]);
    getPermissionListFun();
  }, [selectedTreeKeys]);

  // 获取菜单列表
  const getMenuTreeFun = () => {
    if (outId) {
      $loadding1(true);
      const payload = {
        siteOutId: outId,
        parentOutId: '',
      };
      getMenuTree(payload).then((res) => {
        $loadding1(false);
        if (!res) return;
        $selectedTreeKeys([res[0]?.OutId]);
        $treeList(res);
      });
    }
  };

  // 获取权限列表
  const getPermissionListFun = (txt?) => {
    const [id] = selectedTreeKeys;
    if (id) {
      const paylaod = {
        siteOutId: outId,
        entityId: id,
        searchText: txt || '',
      };
      getPermissionList(paylaod).then((res) => {
        if (!res) return;
        $permissionList(res);
      });
    }
  };

  const appClick = (outId: any) => {
    $outId(outId);
    $permissionList([]);
  };

  // 异步加载菜单
  const onLoadData = (treeNode) => {
    return new Promise((resolve) => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      const payload = {
        siteOutId: outId,
        parentOutId: treeNode.props.dataRef.OutId,
      };
      getMenuTree(payload).then((res: any) => {
        treeNode.props.dataRef.children = res;
        $treeList(updateTreeData(treeList, res, treeNode.props.eventKey));
        resolve();
      });
    });
  };
  // 判断是否是ifream嵌套
  const isIframe = useMemo(() => {
    return location?.hash?.indexOf('permissionFun') != -1;
  }, []);

  const updateTreeData = (list, children, key) => {
    return list.map((node) => {
      if (node.OutId === key) {
        return {
          ...node,
          children,
        };
      }
      if (node.children) {
        return {
          ...node,
          children: updateTreeData(node.children, key, children),
        };
      }
      return node;
    });
  };

  return (
    <div
      className={'main'}
      style={{ height: `calc(${containerHeight} - 144px)` }}
    >
      <div className={'appList'}>
        <AppList outId={outId} appClick={appClick} list={appList} />
      </div>

      <div className={'treeList'}>
        {treeList.length ? (
          <TreeList
            key={outId}
            list={treeList}
            onLoadData={onLoadData}
            selectedKeys={selectedTreeKeys}
            treeClick={(arr) => $selectedTreeKeys(arr)}
          />
        ) : loadding1 ? (
          <Spin className={'spindiv'} />
        ) : (
          <Empty
            className={'spindiv'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>Permission.noData</TextWidget>}
          />
        )}
      </div>

      <div className={`${isIframe ? 'iframePerm' : 'permission'}`}>
        <Permission
          key={selectedTreeKeys[0]}
          treeList={treeList}
          list={permissionList}
          outId={outId}
          menuId={selectedTreeKeys[0]}
          onRefresh={getPermissionListFun}
          permtype={'menu'}
          permConfig={permConfig}
        />
      </div>
    </div>
  );
};

export default Menu;
